package com.yonyou.pmclouds.mob.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.PMControllerConst;
import com.yonyou.pmclouds.basecom.conf.DeployTypeConfiguration;
import com.yonyou.pmclouds.basecom.conf.ProductActiveProperties;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.outter.permission.PermissionInfoQuery;
import com.yonyou.pmclouds.outter.tenant.TenantInfoQuery;
import com.yonyou.pmclouds.project.entity.ProjectConst;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.team.rmiitf.ProjectRefWithTeamQuery;
import com.yonyou.pmclouds.tenant.entity.TenantInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static com.yonyou.pmclouds.outter.tenant.TenantInfoQuery.*;

@RestController
public class PermissionInfoController {
    @Autowired
    private PermissionInfoQuery permQuery;
    @Autowired
    private TenantInfoQuery tenantQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProjectRefWithTeamQuery teamQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProjectSimpleQuery projectSimpleQuery;
    @Autowired(required = false)
    private ProductActiveProperties productActiveProperties;
    @Autowired
    private DeployTypeConfiguration.DeployInfo deployInfo;

    @GetMapping("/mobile/permission/funcs")
    public Set<String> getMobileFuncInfo(@RequestParam("tenantid") String tenantid) {
        Set<String> allPerms = permQuery.getPermisionIntenant(RuntimeEnvironment.getLoginUserId(), tenantid);
        if (allPerms == null) {
            return null;
        }
        Iterator<String> perm = allPerms.iterator();
        while (perm.hasNext()) {
            String code = perm.next();
            if (StringUtils.isEmpty(code) || !code.startsWith("mobile")) {
                perm.remove();
            }
        }
        return allPerms;
    }

    @GetMapping("/mobile/permission/cachedIn")
    public Map<String, Object> cachedInSystem(@RequestParam("tenantid") String tenantid, @RequestParam("projectid") String projectid) throws BusinessException {
        Map<String, Object> result = this.checkTenantProject(tenantid, projectid);
        if (result != null && ("ok".equals(result.get("state")) || "licenseUserExceed".equals(result.get("state")))) {
            return result;
        }
        Map<String, Object> firstLoginInfo = this.getDefaultFirstPageInfo(tenantid);
        if (firstLoginInfo != null && result != null) {
            result.putAll(firstLoginInfo);
        }
        return result;
    }

    @GetMapping("/mobile/permission/checkPerm")
    public Map<String, Object> checkTenantProject(@RequestParam("tenantid") String tenantid, @RequestParam("projectid") String projectid) throws BusinessException {
        Map<String, Object> result = new HashMap<>(3);
        // 是否存在租户中心的权限
        List<TenantInfo> tenants = tenantQuery.getTenantsOfUser(RuntimeEnvironment.getLoginUserId(), DeployTypeConfiguration.getSysId());
        if (tenants == null || tenants.size() == 0) {
            result.put("state", "illegal_tenant");
            return result;
        }
        boolean hasTenant = false;
        for (TenantInfo t : tenants) {
            if (t.getTenantId().equals(tenantid)) {
                hasTenant = true;
                break;
            }
        }
        if (!hasTenant) {
            result.put("state", "illegal_tenant");
            return result;
        }
        //  校验项目是否存在
        int state = teamQuery.checkProjectStatus(RuntimeEnvironment.getLoginUserId(), tenantid, projectid);
        switch (state) {
            case ProjectRefWithTeamQuery.STATUS_OK:
                result.put("state", "ok");
                break;
            case ProjectRefWithTeamQuery.PROJECT_END:
                result.put("state", "project_end");
                break;
            case ProjectRefWithTeamQuery.PROJECT_NOT_EXIST:
                result.put("state", "project_not_exist");

        }

        if (ProjectRefWithTeamQuery.STATUS_OK == state) {
            if (isNeedControl()) {
                //  校验租户的license
                int lic = tenantQuery.checkTenantLicense(tenantid);
                switch (lic) {
                    case LICENSE_SYSERR:
                        result.put("funcs", new String[0]);
                        result.put("state", "licenseSyserr");
                        break;
                    case LICENSE_USER_EXCEED:
                        Set<String> allPerm = getMobilePermissions(RuntimeEnvironment.getLoginUserId(), tenantid);
                        result.put("funcs", allPerm);
                        result.put("state", "licenseUserExceed");
                        break;
                    case LICENSE_OK:
                        Set<String> allPerms = getMobilePermissions(RuntimeEnvironment.getLoginUserId(), tenantid);
                        result.put("funcs", allPerms);
                        break;
                }
            } else {
                Set<String> allPerms = getMobilePermissions(RuntimeEnvironment.getLoginUserId(), tenantid);
                result.put("funcs", allPerms);
            }
        }
        return result;
    }

    private boolean isNeedControl() {
        return DeployTypeConfiguration.DeployInfo.PUBLIC_DEPLOY.equals(deployInfo.getDeployType()) && productActiveProperties.isEnableCtrl();
    }

    @GetMapping("/mobile/permission/firstLogin")
    public Map<String, Object> getDefaultFirstPageInfo(@RequestParam(name = "tenantId", required = false) String tenantId) throws BusinessException {
        // 增加tenantId，允许优先选择某个租户下的项目
        String userid = RuntimeEnvironment.getLoginUserId();
        //  查询用户可用的数据中心
        List<TenantInfo> tenants = tenantQuery.getTenantsOfUser(userid, DeployTypeConfiguration.getSysId());

        if (tenants == null || tenants.size() == 0) {
            return null;
        }
        //  选取第一数据中心查询项目
        TenantInfo finalTenant = null;
        Object finalProject = null;
        if (tenantId != null) {
            for (TenantInfo tenant : tenants) {
                if (tenantId.equals(tenant.getTenantId())) {
                    PageObject<?> projects = teamQuery.queryOfUser(userid, tenantId, new Byte[]{ProjectConst.STATE_GOING},
                            Integer.valueOf(PMControllerConst.DEFAULT_PAGE_PAGE_START), 1000, null);
                    if (projects.getCount() > 0) {
                        finalTenant = tenant;
                        finalProject = (projects.getObjects()[0]);
                    }
                    break;
                }
            }
        }
        if (finalProject == null) {
            for (TenantInfo tenant : tenants) {
                PageObject<?> projects = teamQuery.queryOfUser(userid, tenant.getTenantId(), new Byte[]{ProjectConst.STATE_GOING},
                        Integer.valueOf(PMControllerConst.DEFAULT_PAGE_PAGE_START), 1000, null);
                if (projects.getCount() > 0) {
                    finalTenant = tenant;
                    finalProject = (projects.getObjects()[0]);
                    break;
                }
            }
        }
        if (finalTenant == null) {
            finalTenant = tenants.get(0);
        }
        Map<String, Object> result = new HashMap<>(3);
        result.put("tenant", finalTenant);
        result.put("project", finalProject);
        if (isNeedControl()) {
            int lic = tenantQuery.checkTenantLicense(finalTenant.getTenantId());
            switch (lic) {
                case LICENSE_SYSERR:
                    result.put("funcs", new String[0]);
                    result.put("state", "licenseSyserr");
                    break;
                case LICENSE_USER_EXCEED:
                    Set<String> allPerm = getMobilePermissions(userid, finalTenant.getTenantId());
                    result.put("funcs", allPerm);
                    result.put("state", "licenseUserExceed");
                    break;
                case LICENSE_OK:
                    Set<String> allPerms = getMobilePermissions(userid, finalTenant.getTenantId());
                    result.put("funcs", allPerms);
                    break;
            }
        } else {
            Set<String> allPerms = getMobilePermissions(userid, finalTenant.getTenantId());
            result.put("funcs", allPerms);
        }
        return result;
    }

    private Set<String> getMobilePermissions(String userid, String finalTenant) {
        Set<String> allPerms = permQuery.getPermisionIntenant(userid, finalTenant);
        if (allPerms != null) {
            Iterator<String> perm = allPerms.iterator();
            while (perm.hasNext()) {
                String code = perm.next();
                if (StringUtils.isEmpty(code) || !code.startsWith("mobile")) {
                    perm.remove();
                }
            }
        }
        return allPerms;
    }

    @GetMapping("/perission/func")
    public Set<String> getPermissionInfo(@RequestParam("tenantid") String tenantid) {
        return permQuery.getPermisionIntenant(RuntimeEnvironment.getLoginUserId(), tenantid);
    }

    @GetMapping("/mobile/permission/tenant")
    public List<TenantInfo> getCanLogineTenant() {
        // TODO 是否需要根据项目团队过滤
        return tenantQuery.getTenantsOfUser(RuntimeEnvironment.getLoginUserId(), DeployTypeConfiguration.getSysId());
    }
}
